package com.lczyfz.istep.common.utils.domain;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Properties;

/**
 * Created by chenqk on 2017/5/11.
 */
public class WebHookExecutor {

    public void pull() {
        try {
            String username = "charkey";
            String password = "1@3qweasd";
            String host = "139.162.72.59";
            int port = 22;

            JSch jSch = new JSch();
            Session session = jSch.getSession(username, host, port);
            session.setPassword(password);

            Properties config = new Properties();
            // 当第一次连接服务器时，自动接受新的公钥
            config.put("StrictHostKeyChecking", "no");
            // compression
            config.put("compression.s2c", "zlib@openssh.com,zlib,none");
            config.put("compression.c2s", "zlib@openssh.com,zlib,none");
            config.put("compression_level", "9");

            session.setConfig(config);

            session.connect();

            CommandExecutor executor = new DefaultCommandExecutor(session);

            //exec("ls", "UTF-8", session);
            exec("cd /data/nginx/www/lczywebsite && git pull", "UTF-8", session);

            session.disconnect();
        } catch (JSchException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void exec(String command, String charset, Session session) throws JSchException, IOException {
        ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
        channelExec.setCommand(command);
        channelExec.setInputStream(null);
        channelExec.setErrStream(System.err);
        channelExec.connect();
        InputStream in = channelExec.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in, Charset.forName(charset)));
        String buf = null;
        while ((buf = reader.readLine()) != null) {
            System.out.println(buf);
        }
        reader.close();
        channelExec.disconnect();
    }
}
